package com.gimi.test_jpa.com.gimi.aop;

import com.gimi.test_jpa.com.gimi.util.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import javax.servlet.http.HttpServletRequest;


@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler implements ResponseBodyAdvice<Object> {

    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body==null) {
            //当前返回值可能是void,如果当前controller上面增加了拦截注解，则返回空格式的数据
            if(TransCacheInfoUtil.isResultInterceptor()) {
                BaseResponse rs=new BaseResponse();
                return rs.success();
            }else {
                return body;
            }
        }
        if(request.getURI().getPath().startsWith("/swagger") || body.getClass().getName().startsWith("springfox")) {
            return body;
        }
        if (body instanceof BaseResponse){
            return body;
        }
        if (TransCacheInfoUtil.isResultInterceptor()){
            BaseResponse rs=new BaseResponse();
//            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            rs.setResponseTime(dateFormat.format(new Date()));
//            rs.setBody(body);
            return rs.success(body);
        }
        return body;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public Object jsonErrorHandler(HttpServletRequest request, Exception e) throws Exception {
//            if (e instanceof java.lang.IllegalArgumentException) {
//                log.error(e.getMessage());
//            } else {
//                log.error(e.getMessage(), e);
//            }
            e.printStackTrace();
            BaseResponse<String> baseResponse = new BaseResponse<>();
            if(e instanceof BindException) {
                BindException be=(BindException)e;
                return baseResponse.fail(new Exception(be.getFieldError().getDefaultMessage()));
            }
            return baseResponse.fail(e);
        }
}
